/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2019年05月12日
*   描    述：
*   Copyright (C) 2019 All rights reserved.
*   
================================================================*/


#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
    string reverseWords(string s) {
        int size = s.size();
        if(size == 0)
            return "";

        reverseWord(s, 0, size - 1);
        int i = 0, j = 0;;
        while( i <size ){
            while( i < size && s[i] == ' ' )
                i++;
            j = i + 1;
            while( j < size && s[j] != ' ' )
                j++;
            reverseWord(s, i, j-1);
            i = j + 1;
        }

        cleanspace(s);
        return s;
    }

private:
    void reverseWord(string &s, int start, int end){
        char tmp;
        while( start < end ){
            tmp = s[start];
            s[start++] = s[end];
            s[end--] = tmp;
        }
    }

    void cleanspace(string&s){
        int size = s.size();

        int start = 0, end = 0;
        while(end < size && s[end] == ' ') // skip spaces
            end++;
        while( end < size ){
            while(end < size && s[end] != ' ')// skip non spaces
                s[start++] = s[end++];
            while(end < size && s[end] == ' ')
                end++;
            if(end < size)
                s[start++] = ' '; //copy ' ' to s[start]
        }
        
        s[start] = '\0';
    }
};
